/*
 * Copyright (C) 2010 Graham Allan
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package edu.strath.cis.grallan.findbugs.adaptiveranking.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Uses many comparators to provide an ordering. Comparators are used in order to find an ordering,
 * returning 0 iff all the comparators return 0. <br>
 * <br>
 * StackedComparators are created using the {@link StackedComparatorBuilder}. For example:
 * 
 * <pre>
 * <code>
 * Comparator<MyType> comparator = new StackedComparatorBuilder<MyType>()
 * 										.sortBy(firstComparator)
 * 										.then(secondComparator)
 * 										.then(anyOtherComparator)
 * 										.thenTie();
 * 
 * </code>
 * </pre>
 * 
 * 
 * @author Graham Allan (grallan@cis.strath.ac.uk)
 */
public class StackedComparatorBuilder<T> implements ComparatorBuilder<T> {
	private final List<Comparator<? super T>> comparators = new ArrayList<Comparator<? super T>>();

	public SubsequentComparator<T> sortBy(Comparator<? super T> comparator) {
		comparators.add(comparator);
		return this;
	}

	public SubsequentComparator<T> then(Comparator<? super T> comparator) {
		comparators.add(comparator);
		return this;
	}

	public Comparator<T> thenTie() {
		return new StackedComparator(Collections.unmodifiableList(comparators));
	}

	class StackedComparator implements Comparator<T> {

		private List<Comparator<? super T>> comparators;

		/**
		 * Private constructor, use builder pattern with {@link StackedComparatorBuilder}.
		 * 
		 * @see StackedComparatorBuilder
		 */
		private StackedComparator(List<Comparator<? super T>> comparators) {
			this.comparators = comparators;
		}

		public int compare(T o1, T o2) {
			for (Comparator<? super T> comparator : comparators) {
				int comparisonResult = comparator.compare(o1, o2);
				if (comparisonResult != 0) {
					return comparisonResult;
				}
			}
			return 0;
		}

	}

}
